﻿using AutoMapper;
using H2.NET.Business;
using H2.NET.Common;
using H2.NET.Data.Common;
using H2.NET.Web.Management.Config.Service;
using H2.NET.Web.Pages.SMD.Dto;
using H2.NET.Web.Pages.SMD.Helper;
using H2.NET.Web.Pages.SMD.Model;
using H2.NET.Web.Pages.SMD.Service;
using H2.NET.Web.Workflow.DwzCode;
using H2.NET.Web.Workflow.Helper;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;
using H2.NET.TaskRob;
namespace H2.NET.Web.Pages.SMD
{
    public partial class BatchContract : BasePage
    {

        public IList<t_StoreDataChangeLog> logs = new List<t_StoreDataChangeLog>();

        public string update_logs = "[]";

        public string stores_json = "[]";

        public string step = "";

        public string oldDealer;
        public string newDealer;
        protected void Page_Load(object sender, EventArgs e)
        {
            storeCancelContract.Visible = false;
            deviceCancelContract.Visible = false;
            btn_save.Visible = false;
            DwzAssessment1.Category = "ChangeContract";
            var key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");

            if (key == Constant.PROCESS_CHANGEDEALER)
            {
                //  storeCancelContract.Visible = true;  2016-11-08 隐藏门店合同信息
                deviceCancelContract.Visible = true;
                var process = TaskAPI.GetVariableBySingleValue("ParentProcess");
                var incident = TaskAPI.GetVariableBySingleValue("ParentIncident");
                var parentMaster = (t_StoreMasterData._Process == process & t_StoreMasterData._Incident == incident)
                    .ListFirst<t_StoreMasterData>();
                if ((parentMaster.DealerCode ?? "").Split('|').Length > 1)
                {
                    var oD = DealerService.GetById(Utils.StrToInt(parentMaster.DealerCode.Split('|')[1], 0));
                    var nD = DealerService.GetById(Utils.StrToInt(parentMaster.DealerCode.Split('|')[0], 0));
                    if (oD != null)
                    {
                        oldDealer = "原经销商编号:" + oD.DealerCode + " 原经销商名称:" + oD.Name;
                    }
                    if (nD != null)
                    {
                        newDealer = "现经销商编号:" + nD.DealerCode + " 现经销商名称:" + nD.Name;
                    }
                }

            }


            if (!IsPostBack)
            {
                InitDropDownList();
                if (ReadOnly()) return;

                step = TaskAPI.Step;

                Session.Remove("StoreDataChangeLog_Contract");
                Session.Remove("StoreDataChangeLog_DeviceContract");
                btn_submit.Visible = TaskAPI.IsAllowSubmit;
                if (IsOverFlow)
                {
                    btn_submit.Visible = false;
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "info_tip", "$.jBox.tip('" + string.Format("该表单正在被“{0}”处理，请稍后再试。", RobUser) + "', 'info');", true);
                    return;
                }

                uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");

                #region Submit Data
                if (TaskAPI.Step == "Submit Data")
                {
                    btn_save.Visible = true;
                    var storeids = "";
                    storeids = TaskAPI.GetVariableBySingleValue("BlankVlue");
                    if (storeids == "")
                    {
                        var storeMasterData = (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident).ListFirst<t_StoreMasterData>();
                        if (storeMasterData != null)
                            storeids = storeMasterData.BeforeUpgradedType;
                    }
                    //先根据storeid关联到storeContractDto类,再把门店合同和设备合同绑上去。
                    if (storeids != null && storeids != "")
                    {
                        #region 根据storeid初始化StoreContractDto
                        var stores = (t_smd_Store._StoreID.In(storeids.Split('|'))).List<t_smd_Store>(Storage.Context3).ToList();
                        Mapper.CreateMap<t_smd_Store, StoreContractDto>();
                        var storelist = Mapper.Map<List<t_smd_Store>, List<StoreContractDto>>(stores);
                        #endregion

                        #region 把设备合同和门店合同帮到StoreContractDto
                        var deviceContracts = (t_smd_ContractDevice._StoreID.In(storelist.Select(t => t.StoreID))).List<t_smd_ContractDevice>(Storage.Context3).ToList();
                        foreach (var conDto in storelist)
                        {
                            #region 绑定设备合同到
                            conDto.devices = new List<ContractDeviceDto>();
                            foreach (var deviceContract in deviceContracts)
                            {
                                if (conDto.StoreID == deviceContract.StoreID)
                                {
                                    Mapper.CreateMap<t_smd_ContractDevice, ContractDeviceDto>();
                                    ContractDeviceDto deviceDto = Mapper.Map<t_smd_ContractDevice, ContractDeviceDto>(deviceContract);
                                    if (TaskAPI.GetVariableBySingleValue("AutoBusinessKey") ==
                                                Constant.PROCESS_CHANGEDEALER)
                                    {
                                        var deviceCancel = ContractDeviceService.getCotractDeviceCancelByDeviceID(deviceContract.DeviceID);

                                        Mapper.CreateMap<t_smd_ContractDevice_Cancel, ContractDeviceCancelDto>();
                                        var deviceCancelDto = Mapper.Map<t_smd_ContractDevice_Cancel, ContractDeviceCancelDto>(deviceCancel);
                                        deviceDto.DeviceCancel = deviceCancelDto;
                                    }
                                    conDto.devices.Add(deviceDto);
                                }
                            }
                            #endregion

                            #region 获取门店合同并放到storeContractDto里
                            var storecontract = ContractService.GetContractByStoreID(conDto.StoreID);
                            Mapper.CreateMap<t_smd_Contract, ContractDto>();
                            var contractDto = Mapper.Map<t_smd_Contract, ContractDto>(storecontract);
                            conDto.contract = contractDto;
                            #endregion

                            #region 获取门店终止合同并绑定
                            if (key == Constant.PROCESS_CHANGEDEALER && storecontract != null)
                            {
                                var ContractCancel = ContractService.GetContractCancelByStoreID(conDto.StoreID);
                                Mapper.CreateMap<t_smd_Contract_Cancel, ContractCancelDto>();
                                var cancelDto = Mapper.Map<t_smd_Contract_Cancel, ContractCancelDto>(ContractCancel);
                                conDto.contract.StoreCancel = cancelDto;
                            }
                            #endregion
                        }
                        #endregion



                        #region 判断是否是退回
                        #region 如果是退回重新初始化合同信息
                        IsoDateTimeConverter iso = new IsoDateTimeConverter();
                        iso.DateTimeFormat = "yyyy-MM-dd";
                        stores_json = JsonConvert.SerializeObject(storelist, iso);
                        lb_selectData.Visible = false;
                        if (!String.IsNullOrEmpty(TaskAPI.GetVariableBySingleValue("Checked")))
                        {
                            assessment.Visible = true;
                        }
                        #endregion

                        storelist = InitStoreContract(storelist);

                        iso = new IsoDateTimeConverter();
                        iso.DateTimeFormat = "yyyy-MM-dd";
                        stores_json = JsonConvert.SerializeObject(storelist, iso);
                        #endregion
                    }

                    if (Session["StoreDataChangeLog_Contract"] != null)
                    {
                        var sdc_logs = Session["StoreDataChangeLog_Contract"] as List<t_StoreDataChangeLog>;
                        Mapper.CreateMap<t_StoreDataChangeLog, StoreDataChangeLogDto>();
                        var list = Mapper.Map<List<t_StoreDataChangeLog>, List<StoreDataChangeLogDto>>(sdc_logs);
                        IsoDateTimeConverter iso = new IsoDateTimeConverter();
                        iso.DateTimeFormat = "yyyy-MM-dd";
                        update_logs = JsonConvert.SerializeObject(list, iso);
                    }



                }
                #endregion

                #region 审批环节
                else
                {
                    #region 加载数据并显示

                    t_StoreMasterData storeMasterData = (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident).ListFirst<t_StoreMasterData>();
                    if (storeMasterData == null)
                    {
                        btn_submit.Visible = false;
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "info_tip", "$.jBox.tip('加载数据失败，请关闭页面重新打开！', 'info');", true);
                        return;
                    }

                    hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                    hl_ExportPdf.Visible = true;

                    uc_head1.date = storeMasterData.SubmitDate.Value.ToString("yyyy-MM-dd");

                    assessment.Visible = true;
                    var list = new List<StoreContractDto>();
                    list = InitStoreContract(list);
                    IsoDateTimeConverter iso = new IsoDateTimeConverter();
                    iso.DateTimeFormat = "yyyy-MM-dd";
                    stores_json = JsonConvert.SerializeObject(list, iso);
                    #endregion

                    switch (TaskAPI.Step)
                    {
                        case "Data Check":
                            break;
                        case "Manager Approve":
                            FileUpload.Visible = true;
                            break;
                        case "DMO Commit":
                            break;
                    }

                    lb_selectData.Visible = false;
                }
                #endregion

                InitUpdateLogs();
            }
        }

        #region 只读表单

        private bool ReadOnly()
        {
            if (AksRequest.GetString("readonly") == "1")
            {
                // 只读表单，释放抢占
                OpenTasksInstance.OpenTasks.SetTaskClose(TaskAPI.Process, TaskAPI.Incident, TaskAPI.Step);

                step = "readOnly";
                btn_save.Visible = false;
                lb_selectData.Visible = false;
                assessment.Visible = true;
                btn_submit.Visible = false;
                DwzAssessment1.Visible = false;

                #region 加载数据并显示
                // 门店数据
                t_StoreMasterData storeMasterData = (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident).ListFirst<t_StoreMasterData>();
                if (storeMasterData == null)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "info_tip", "$.jBox.tip('该流程还没有提交过，没有任何数据！', 'info');", true);
                    return true;
                }

                uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                uc_head1.date = storeMasterData.SubmitDate.Value.ToString("yyyy-MM-dd");
                uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");

                assessment.Visible = true;


                var list = new List<StoreContractDto>();

                list = InitStoreContract(list);

                IsoDateTimeConverter iso = new IsoDateTimeConverter();
                iso.DateTimeFormat = "yyyy-MM-dd";
                stores_json = JsonConvert.SerializeObject(list, iso);
                #endregion

                InitUpdateLogs();


                hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                hl_ExportPdf.Visible = true;
                btn_print.Visible = true;

                return true;
            }

            return false;
        }
        #endregion

        private bool Send(ref string return_msg)
        {
            bool flag = false;
            try
            {
                #region 数据验证
                if (TaskAPI.Step == "Submit Data" && TaskAPI.IsAllowSubmit) // 如果是退回的情况，不存在验证
                {
                    if (Session["StoreDataChangeLog_Contract"] == null && Session["StoreDataChangeLog_DeviceContract"] == null)
                    {
                        return_msg = "至少选择修改一项";
                        return false;
                    }
                }

                if (DwzAssessment1.Assessment.Remark == "")
                {
                    if (DwzAssessment1.Assessment.Opinion == "2")
                    {
                        return_msg = "如果驳回此流程,请在状态备注中填写放弃流程的原因";
                        return false;
                    }
                    if (DwzAssessment1.Assessment.Opinion == "0")
                    {
                        return_msg = "如果退回此流程,请在状态备注中填写退回的原因";
                        return false;
                    }
                }
                #endregion

                #region 引擎传值
                if (TaskAPI.Step == "Submit Data")
                {
                    TaskAPI["IsBatch"] = "批量";
                    TaskAPI["IsContractChange"] = 1;
                    TaskAPI["Remark_by_Initiator"] = DwzAssessment1.Assessment.Remark;
                    if (TaskAPI.Summary.Contains("退回"))
                    {
                        TaskAPI.Summary = "合同信息区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary);
                    }
                    else
                    {
                        TaskAPI.Summary = "合同信息区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary) + "-" + TaskAPI.GetVariableBySingleValue("Region");
                    }

                }
                else
                {
                    TaskAPI["ApproveResult"] = DwzAssessment1.Assessment.Opinion;
                    TaskAPI["TaskID"] = TaskAPI.TaskID;
                    if (TaskAPI.Step == "Data Check")
                    {
                        TaskAPI["Checked"] = DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "1")
                        {
                            TaskAPI.Summary = "全国合同负责人审核/" + TaskHelper.getSummary(TaskAPI.Summary);
                        }
                        else
                        {
                            TaskAPI.Summary = "(退回)提交合同信息变更/" + TaskHelper.getSummary(TaskAPI.Summary);
                        }
                    }
                    if (TaskAPI.Step == "Manager Approve")
                    {
                        TaskAPI["Approved"] = DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "1")
                            TaskAPI.Summary = "合同信息DMO导入核查/" + TaskHelper.getSummary(TaskAPI.Summary);
                        else
                            TaskAPI.Summary = "(退回)合同信息区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary);

                    }
                    else if (TaskAPI.Step == "DMO Commit")
                    {
                        return_msg = "数据更新到主数据库中时出现错误，请跟踪并处理。";
                        TaskAPI["Commited"] = DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "0")
                            TaskAPI.Summary = "(退回)全国合同负责人审核/" + TaskHelper.getSummary(TaskAPI.Summary);
                    }
                }

                #endregion

                #region 提交步骤

                string step = string.Empty;
                Storage.TransactionExecute(o =>
                {
                    #region 业务流程、审批意见记录

                    t_Assessment ass = DwzAssessment1.Assessment;
                    var lastAss = (t_Assessment.incident == TaskAPI.Incident & t_Assessment.opinionText != "暂存" & t_Assessment.process == TaskAPI.Process).ListFirst<t_Assessment>("time desc");
                    if ((lastAss != null && lastAss.Step != TaskAPI.Step) || lastAss == null)
                    {
                        Storage.Save(Storage.Context1, ass);
                    }
                    else
                    {
                        Logging.GetLogger().Info("=================表单已重复提交======================");
                        Logging.GetLogger().Info("TaskAPI.Step:" + TaskAPI.Step);
                        Logging.GetLogger().Info("TaskAPI.UserFullName:" + TaskAPI.UserFullName);
                        Logging.GetLogger().Info("时间：" + DateTime.Now);
                        Logging.GetLogger().Info("UserAPI.UserName:" + UserAPI.UserName);
                        Logging.GetLogger().Info("======================================================");
                        throw new Exception("该表单的步骤已经提交过了，请联系IT。");
                    }
                    Storage.Save(Storage.Context1, ass);
                    var key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
                    #endregion

                    #region “Submit Data”步骤
                    if (TaskAPI.Step == "Submit Data")
                    {

                        var storeMasterData = (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident).ListFirst<t_StoreMasterData>();
                        if (storeMasterData == null)
                        {
                            storeMasterData = new t_StoreMasterData();
                            storeMasterData.SubmitDate = DateTime.Now;
                            storeMasterData.Creator = TaskAPI.UserName;
                            storeMasterData.ApplicationNO = uc_head1.applicationNo;
                            storeMasterData.Process = TaskAPI.Process;
                            storeMasterData.Incident = TaskAPI.Incident;
                            storeMasterData.BusinessKey = ass.BusinessKey;
                            storeMasterData.BusinessProcess = ass.BusinessProcess;
                            Storage.Save(Storage.Context1, storeMasterData);
                        }


                        var sdc_logs = Session["StoreDataChangeLog_Contract"] as List<t_StoreDataChangeLog>;
                        sdc_logs = sdc_logs.Where(t => t.UserID == UserAPI.UserFullName).ToList();
                        sdc_logs.ForEach(log => log.AssessmentID = ass.ID);
                        Storage.Save(sdc_logs.ToArray());

                        var deviceDataChangeLogs = Session["StoreDataChangeLog_DeviceContract"] as List<t_StoreDataChangeLog>;
                        deviceDataChangeLogs.ForEach(log => log.AssessmentID = ass.ID);
                        Storage.Save(deviceDataChangeLogs.ToArray());
                        if (key.Equals(Constant.PROCESS_CHANGEOTHER))
                        {
                            BusinessService.SaveChildProcess(TaskAPI, ass, "active");

                            var stores = new List<t_smd_Store>();
                            var dealers = new List<t_smd_Dealer>();
                            foreach (var log in sdc_logs)
                            {
                                var contract = ContractService.GetContractByID(Utils.StrToInt(log.DataID, 0));
                                var store = StoreService.GetSmdStoreById(contract.StoreID.Value);
                                var dealer = DealerService.GetById(store.DealerID.Value);
                                if (!stores.Select(s => s.StoreID).Contains(store.StoreID))
                                {
                                    stores.Add(store);
                                }
                                if (!dealers.Select(s => s.DealerID).Contains(dealer.DealerID))
                                {
                                    dealers.Add(dealer);
                                }
                            }
                            dealers = dealers.Distinct().ToList<t_smd_Dealer>();

                            var devices = new List<t_smd_Device>();
                            foreach (var log in deviceDataChangeLogs)
                            {
                                var device = DeviceService.GetSmdDeviceById(Utils.StrToInt(log.DataID, 0));
                                if (!devices.Select(t => t.DeviceID).Contains(device.DeviceID))
                                {
                                    devices.Add(device);
                                }
                            }

                            BusinessService.saveProcessRelation(TaskAPI, ass, null, null, null, null, stores, devices, dealers);
                        }
                        if (key == Constant.PROCESS_CHANGEOTHER && !TaskAPI.Summary.Contains("退回"))
                        {
                            TaskAPI.Summary = "合同信息区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary) + " - " + ass.BusinessKey;
                        }
                    }
                    #endregion

                    #region “Data Check”,“Manager Approve”步骤
                    if (TaskAPI.Step == "Data Check" || TaskAPI.Step == "Manager Approve")
                    {
                        if (DwzAssessment1.Assessment.Opinion == "2")
                        {
                            flag = TaskHelper.Abort(TaskAPI.TaskID, DwzAssessment1.Assessment.Remark, TaskAPI.GetVariableBySingleValue("Applicator"));

                            BusinessService.SaveChildProcess(TaskAPI, ass, "abort", DwzAssessment1.Assessment.Remark, DwzAssessment1.Assessment.Time, ass.UserFullName);
                        }
                        else
                        {
                            var sdc_logs = Session["StoreDataChangeLog_Contract"] as List<t_StoreDataChangeLog>;
                            sdc_logs = sdc_logs.Where(t => t.UserID == UserAPI.UserFullName).ToList();
                            sdc_logs.ForEach(log => log.AssessmentID = ass.ID);
                            Storage.Save(sdc_logs.ToArray());


                            var deviceDataChangeLogs = Session["StoreDataChangeLog_DeviceContract"] as List<t_StoreDataChangeLog>;
                            deviceDataChangeLogs.ForEach(log => log.AssessmentID = ass.ID);
                            Storage.Save(deviceDataChangeLogs.ToArray());

                            (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident).Edit<t_StoreMasterData>(p =>
                            {
                                step = p.Step = TaskAPI.Step;
                            });
                        }
                    }
                    #endregion

                    #region “DMO Commit”步骤
                    if (TaskAPI.Step == "DMO Commit")
                    {
                        if (DwzAssessment1.Assessment.Opinion == "1")
                        {
                            var assessments = (t_Assessment.process == TaskAPI.Process & t_Assessment.incident == TaskAPI.Incident).List<t_Assessment>();

                            #region 变更日志

                            Mapper.CreateMap<t_StoreDataChangeLog, t_smd_StoreDataChangeLog>();

                            var mdc_changelogs = Session["StoreDataChangeLog_Contract"] as List<t_StoreDataChangeLog>;

                            List<t_smd_StoreDataChangeLog> smd_changelogs = Mapper.Map<List<t_StoreDataChangeLog>, List<t_smd_StoreDataChangeLog>>(mdc_changelogs);
                            foreach (t_smd_StoreDataChangeLog smd_changelog in smd_changelogs)
                            {
                                smd_changelog.EntityState._FieldState.Remove("LogID");
                            }
                            Storage.Save(Storage.Context3, smd_changelogs.ToArray());

                            var deviceDataChangeLogs = Session["StoreDataChangeLog_DeviceContract"] as List<t_StoreDataChangeLog>;
                            List<t_smd_StoreDataChangeLog> smd_devicechangelogs = Mapper.Map<List<t_StoreDataChangeLog>, List<t_smd_StoreDataChangeLog>>(deviceDataChangeLogs);
                            foreach (t_smd_StoreDataChangeLog smd_changelog in smd_devicechangelogs)
                            {
                                smd_changelog.EntityState._FieldState.Remove("LogID");
                            }
                            Storage.Save(Storage.Context3, deviceDataChangeLogs.ToArray());

                            #endregion

                            #region 更新主数据
                            foreach (t_StoreDataChangeLog mdc_changelog in mdc_changelogs)
                            {
                                if (mdc_changelog.Category == "BatchChangeContract")
                                {
                                    var id = mdc_changelog.DataID;

                                    t_smd_Contract contract = (t_smd_Contract._ContractID == id).ListFirst<t_smd_Contract>(Storage.Context3);

                                    if (contract == null) continue;

                                    Type type = contract.GetType();

                                    PropertyInfo propertyInfo = type.GetProperty(mdc_changelog.FieldName);
                                    propertyInfo.SetValue(contract, EntityBase.ChangeType(mdc_changelog.AfterValue, propertyInfo.PropertyType), null);

                                    Storage.Save(Storage.Context3, contract);
                                }

                            }

                            foreach (t_StoreDataChangeLog mdc_changelog in deviceDataChangeLogs)
                            {

                                if (mdc_changelog.Category == "BatchChangeContractDevice")
                                {
                                    var id = mdc_changelog.DataID;

                                    t_smd_ContractDevice contractDevice = (t_smd_ContractDevice._ContractDeviceID == id).ListFirst<t_smd_ContractDevice>(Storage.Context3);

                                    if (contractDevice == null) continue;

                                    Type type = contractDevice.GetType();

                                    PropertyInfo propertyInfo = type.GetProperty(mdc_changelog.FieldName);
                                    propertyInfo.SetValue(contractDevice, EntityBase.ChangeType(mdc_changelog.AfterValue, propertyInfo.PropertyType), null);

                                    Storage.Save(Storage.Context3, contractDevice);
                                }
                            }

                            #endregion

                            (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident).Edit<t_StoreMasterData>(p =>
                            {
                                step = p.Step = "Finish";
                            });
                            BusinessService.SaveChildProcess(TaskAPI, DwzAssessment1.Assessment, "Finish");
                        }
                        else if (DwzAssessment1.Assessment.Opinion == "2")
                        {
                            flag = TaskHelper.Abort(TaskAPI.TaskID, DwzAssessment1.Assessment.Remark, TaskAPI.GetVariableBySingleValue("Applicator"));
                            BusinessService.SaveChildProcess(TaskAPI, ass, "abort", DwzAssessment1.Assessment.Remark, DwzAssessment1.Assessment.Time, ass.UserFullName);
                        }
                    }
                    #endregion
                });
                if (DwzAssessment1.Assessment.Opinion != "2")
                {
                    // 变更列表
                    TaskAPI["Content"] = ChangeLogService.GenerateExcel(TaskAPI);
                    flag = TaskAPI.Send();

                }
                Session.Remove("StoreDataChangeLog_Contract");

                //如果数据库写入成功且流程发起成功的情况，将业务表数据与流程实例号进行关联
                if (TaskAPI.Step == "Submit Data")
                {
                    (t_Assessment.process == TaskAPI.Process & t_Assessment.incident == 0 & t_Assessment.assignedToUserName == UserAPI.UserName).Edit<t_Assessment>(p =>
                    {
                        p.Incident = TaskAPI.Incident;
                    });

                    (t_Attachment.process == TaskAPI.Process & t_Attachment.incident == 0 & t_Attachment.username == UserAPI.UserName).Edit<t_Attachment>(p =>
                    {
                        p.Incident = TaskAPI.Incident;
                    });
                }
                #endregion
            }
            catch (Exception ex)
            {
                return_msg = ex.Message.Replace("\"", "\\\"");
                Logging.GetLogger().Error("调用BatchContract.aspx方法Send_Click出错：" + ex);
                flag = false;
            }
            return flag;
        }

        protected void btn_submit_Click(object sender, EventArgs e)
        {
            string return_msg = string.Empty;
            if (Send(ref return_msg))
            {
                btn_submit.Visible = false;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "info_prompt", "$.jBox.prompt('操作成功！','提示', 'info', { closed: function () { window.opener.reload(); closeWin(); } });", true);
                return;
            }
            else
            {
                return_msg = string.IsNullOrEmpty(return_msg) ? Resources.Global.C_00_Failed : return_msg;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "info_tip", "$.jBox.prompt('" + return_msg + "','提示', 'info');", true);
                return;
            }
        }

        #region 暂存按钮事件

        protected void btn_Save_Click(object sender, EventArgs e)
        {
            var ass = DwzAssessment1.Assessment;
            ass.OpinionText = "暂存";
            Storage.Save(Storage.Context1, ass);
            var assID = ass.ID;
            if (ass.ID == null)
            {
                assID = AssessmentService.GetIdsByTaskApi(TaskAPI)[0];
            }

            var storeMasterData = (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident).ListFirst<t_StoreMasterData>();
            if (storeMasterData == null)
            {
                storeMasterData = new t_StoreMasterData();
                storeMasterData.SubmitDate = DateTime.Now;
                storeMasterData.Creator = TaskAPI.UserName;
                storeMasterData.ApplicationNO = uc_head1.applicationNo;
                storeMasterData.Process = TaskAPI.Process;
                storeMasterData.Incident = TaskAPI.Incident;
                Storage.Save(Storage.Context1, storeMasterData);
            }

            var sdc_logs = Session["StoreDataChangeLog_Contract"] as List<t_StoreDataChangeLog>;
            var device_logs = Session["StoreDataChangeLog_DeviceContract"] as List<t_StoreDataChangeLog>;
            var changeLogs = sdc_logs.Union(device_logs);

            var storeDataIds = changeLogs.Where(c => c.Category == "BatchChangeContract").Select(t => Convert.ToInt32(t.DataID)).Distinct();
            var _deviceDataIds = changeLogs.Where(c => c.Category == "BatchChangeContractDevice").Select(t => Convert.ToInt32(t.DataID)).Distinct();

            //如果门店没变过但是设备变更也要算进去。                                                
            if (_deviceDataIds != null && _deviceDataIds.Count() > 0)
            {
                var storeDeviceIds = new List<int>();
                if ((t_smd_ContractDevice._ContractDeviceID.In(_deviceDataIds)).List<t_smd_ContractDevice>(Storage.Context3).Count > 0)
                {
                    storeDeviceIds = (t_smd_ContractDevice._ContractDeviceID.In(_deviceDataIds)).List<t_smd_ContractDevice>(Storage.Context3).Select(t => Convert.ToInt32(t.StoreID)).Distinct().ToList<int>();
                }
                var storeIds = new List<int>();
                if (storeDataIds.Count() > 0)
                {
                    storeIds = (t_smd_Contract._ContractID.In(storeDataIds)).List<t_smd_Contract>(Storage.Context3).Select(t => Convert.ToInt32(t.StoreID)).Distinct().ToList<int>();
                }
                storeIds = storeIds.Union(storeDeviceIds).ToList<int>();
                storeIds = storeIds.Distinct().ToList<int>();
                storeDataIds = storeIds.Where(t => t != 0);
            }

            sdc_logs = sdc_logs.Where(t => t.UserID == UserAPI.UserFullName).ToList();
            sdc_logs.ForEach(log => log.AssessmentID = assID);
            Storage.Save(sdc_logs.ToArray());

            var storeids = "";
            foreach (var log in sdc_logs)
            {
                storeids += log.DataID + "|";
            }

            var storeidEs = storeids.Split('|');
            var ss = storeidEs.GroupBy(p => p).Select(p => p.Key).ToArray();
            var storeIDS = "";
            foreach (var s in ss)
            {
                if (s != "")
                    storeIDS += s + "|";
            }

            storeMasterData.BeforeUpgradedType = storeIDS;
            Storage.Save(Storage.Context1, storeMasterData);


            var deviceDataChangeLogs = Session["StoreDataChangeLog_DeviceContract"] as List<t_StoreDataChangeLog>;
            deviceDataChangeLogs.ForEach(log => log.AssessmentID = assID);
            Storage.Save(deviceDataChangeLogs.ToArray());
            ScriptManager.RegisterStartupScript(this, GetType(), "info_prompt", "$.jBox.prompt('操作成功！','提示', 'info', { closed: function () { window.opener.reload(); closeWin(); } });", true);
        }

        #endregion

        private void InitDropDownList()
        {
            ConfigService configService = new ConfigService();

            #region 合同性质
            DataTable nature = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_HTXZ') order by seq").Tables[0];
            StoreNature.AppendDataBoundItems = true;
            StoreCancelNature.AppendDataBoundItems = true;

            foreach (DataRow row in nature.Rows)
            {
                StoreNature.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
                StoreCancelNature.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));

            }
            DeviceNature.AppendDataBoundItems = true;
            DeviceCancelNature.AppendDataBoundItems = true;
            foreach (DataRow row in nature.Rows)
            {
                DeviceNature.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
                DeviceCancelNature.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion

            #region 合同归属
            DataTable affiliation =
                configService.GetList("ParentId = (select configid from t_smd_Config where code='S_HTGS') order by seq").Tables[0];
            //门店
            StoreAffiliation.AppendDataBoundItems = true;
            StoreCancelAffiliation.AppendDataBoundItems = true;
            //设备
            DeviceAffiliation.AppendDataBoundItems = true;
            DeviceCancelAffiliation.AppendDataBoundItems = true;

            foreach (DataRow row in affiliation.Rows)
            {
                StoreAffiliation.Items.Add(new ListItem(row["Name"].ToString(), row["Value"].ToString()));
                StoreCancelAffiliation.Items.Add(new ListItem(row["Name"].ToString(), row["Value"].ToString()));
                DeviceAffiliation.Items.Add(new ListItem(row["Name"].ToString(), row["Value"].ToString()));
                DeviceCancelAffiliation.Items.Add(new ListItem(row["Name"].ToString(), row["Value"].ToString()));
            }
            #endregion

            #region 店面合同类型
            DataTable dt_StoreContractType = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_DMHTLX') order by seq").Tables[0];
            StoreContractType.AppendDataBoundItems = true;
            StoreCancelContractType.AppendDataBoundItems = true;
            foreach (DataRow row in dt_StoreContractType.Rows)
            {
                StoreContractType.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
                StoreCancelContractType.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion

            #region 设备合同类型
            DataTable dt_DeviceConractType = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_SBHTLX') order by seq").Tables[0];
            DeviceContractType.AppendDataBoundItems = true;
            DeviceCancelContractType.AppendDataBoundItems = true;
            foreach (DataRow row in dt_DeviceConractType.Rows)
            {
                DeviceContractType.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
                // DeviceCancelContractType.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));

            }
            //20170106 add
            DeviceCancelContractType.Items.Add(new ListItem("设备终止投放及三方转移协议", "设备终止投放及三方转移协议"));
            DeviceCancelContractType.Items.Add(new ListItem("合同终止及三方转移合同", "合同终止及三方转移合同"));

            #endregion

            #region 合同版本号
            var tStoreContractSN = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_HTBBH') order by seq").Tables[0];
            StoreContractSN.AppendDataBoundItems = true;

            foreach (DataRow row in tStoreContractSN.Rows)
            {
                StoreContractSN.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }

            StoreCancelContractSN.AppendDataBoundItems = true;
            StoreCancelContractSN.Items.Add(new ListItem("Contract-TT-1701A", "Contract-TT-1701A")); //20161229 Add
            StoreCancelContractSN.Items.Add(new ListItem("1306A", "1306A"));

            #endregion

            #region 设备合同版本号
            var tDeviceContractSN = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_SBBBH') order by seq").Tables[0];
            DeviceContractSN.AppendDataBoundItems = true;

            foreach (DataRow row in tDeviceContractSN.Rows)
            {
                DeviceContractSN.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }

            DeviceCancelContractSN.AppendDataBoundItems = true;
            DeviceCancelContractSN.Items.Add(new ListItem("Contract-TT-1701A", "Contract-TT-1701A")); //20161229 Add
            DeviceCancelContractSN.Items.Add(new ListItem("1306A", "1306A"));

            #endregion

            #region 甲方
            var tContractParty = configService.GetList("ParentId = (select configid from t_smd_Config where code = 'HTJF')").Tables[0];
            StoreParty.AppendDataBoundItems = true;
            StoreCancelParty.AppendDataBoundItems = true;
            DeviceParty.AppendDataBoundItems = true;
            DeviceCancelParty.AppendDataBoundItems = true;
            foreach (DataRow row in tContractParty.Rows)
            {
                StoreParty.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
                StoreCancelParty.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
                DeviceParty.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
                DeviceCancelParty.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion
        }

        private void InitUpdateLogs()
        {
            if (Session["StoreDataChangeLog_Contract"] == null) return;

            var sdc_logs = Session["StoreDataChangeLog_Contract"] as List<t_StoreDataChangeLog>;

            Mapper.CreateMap<t_StoreDataChangeLog, StoreDataChangeLogDto>();
            var list = Mapper.Map<List<t_StoreDataChangeLog>, List<StoreDataChangeLogDto>>(sdc_logs);
            IsoDateTimeConverter iso = new IsoDateTimeConverter();
            iso.DateTimeFormat = "yyyy-MM-dd";
            update_logs = JsonConvert.SerializeObject(list, iso);
        }

        private List<StoreContractDto> InitStoreContract(List<StoreContractDto> storelist)
        {
            var key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
            #region 找到变更日志
            var assessments = (t_Assessment.process == TaskAPI.Process
            & t_Assessment.incident == TaskAPI.Incident).List<t_Assessment>();
            if (assessments.Count > 0)
            {
                logs = (t_StoreDataChangeLog._AssessmentID.In(assessments.Select(t => t.ID))).List<t_StoreDataChangeLog>(null, " logid desc ");
            }
            if (logs.Count > 0)
            {
                var result_logs = logs.Distinct(new StoreDataChangeLogComparer()).ToList();
                Session["StoreDataChangeLog_Contract"] = logs.Where(t => t.Category == "BatchChangeContract").ToList();
                Session["StoreDataChangeLog_DeviceContract"] = logs.Where(t => t.Category == "BatchChangeContractDevice").ToList();


                #region 通过变更日志判断哪些门店变更过了
                var storeDataIds = logs.Where(c => c.Category == "BatchChangeContract").Select(t => Convert.ToInt32(t.DataID)).Distinct();
                var _deviceDataIds = logs.Where(c => c.Category == "BatchChangeContractDevice").Select(t => Convert.ToInt32(t.DataID)).Distinct();

                //如果门店没变过但是设备变更也要算进去。                                                
                if (_deviceDataIds != null && _deviceDataIds.Count() > 0)
                {
                    var storeDeviceIds = new List<int>();
                    if (
                        (t_smd_ContractDevice._ContractDeviceID.In(_deviceDataIds)).List<t_smd_ContractDevice>(
                            Storage.Context3).Count > 0)
                    {
                        storeDeviceIds =
                            (t_smd_ContractDevice._ContractDeviceID.In(_deviceDataIds)).List<t_smd_ContractDevice>(
                                Storage.Context3).Select(t => Convert.ToInt32(t.StoreID)).Distinct().ToList<int>();
                    }
                    var storeIds = new List<int>();
                    if (storeDataIds.Count() > 0)
                    {
                        storeIds =
                            (t_smd_Contract._ContractID.In(storeDataIds)).List<t_smd_Contract>(Storage.Context3)
                                .Select(t => Convert.ToInt32(t.StoreID))
                                .Distinct()
                                .ToList<int>();
                    }
                    storeIds = storeIds.Union(storeDeviceIds).ToList<int>();
                    storeIds = storeIds.Distinct().ToList<int>();
                    storeDataIds = storeIds.Where(t => t != 0);
                }
                else
                {
                    var storeIds = new List<int>();
                    if (storeDataIds.Count() > 0)
                    {
                        storeIds =
                            (t_smd_Contract._ContractID.In(storeDataIds)).List<t_smd_Contract>(Storage.Context3)
                                .Select(t => Convert.ToInt32(t.StoreID))
                                .Distinct()
                                .ToList<int>();
                    }
                    storeDataIds = storeIds.Where(t => t != 0);
                }

                #endregion
                var newStorelist = new List<StoreContractDto>();

                #region 加载变更的门店合同信息

                //var storeids = "";
                //storeids = TaskAPI.GetVariableBySingleValue("BlankVlue");
                //if (storeids == "")
                //{
                //    var storeMasterData = (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident).ListFirst<t_StoreMasterData>();
                //    if (storeMasterData != null)
                //        storeids = storeMasterData.BeforeUpgradedType;
                //}
                ////不管有没有变更，加载全部已选择合同 add by zsz  2017/03/15
                //if (storeids != null && storeids != "")
                //{
                //    var storeContract = (t_smd_Store._StoreID.In(storeids.Split('|'))).List<t_smd_Store>(Storage.Context3).ToList();
                //    //var storeContract = (t_smd_Store._StoreID.In(storeDataIds)).List<t_smd_Store>(Storage.Context3).ToList();
                //    foreach (var store in storeContract)
                //    {
                //        Mapper.CreateMap<t_smd_Store, StoreContractDto>();
                //        newStorelist.Add(Mapper.Map<t_smd_Store, StoreContractDto>(store));
                //    }

                //    var contractList = (t_smd_Contract._StoreID.In(storeDataIds)).List<t_smd_Contract>(Storage.Context3).ToList();
                //    foreach (var store in newStorelist)
                //    {
                //        var contract = (t_smd_Contract._StoreID == store.StoreID).ListFirst<t_smd_Contract>(Storage.Context3);
                //        if (contract != null)
                //        {
                //            var storeContractLog = result_logs.Where(t => t.DataID == contract.ContractID.ToString() & t.Category == "BatchChangeContract").ToList();
                //            if (storeContractLog.Count > 0)
                //            {
                //                contract = DataHelper<t_smd_Contract>.Reload(contract, storeContractLog);
                //            }
                //            Mapper.CreateMap<t_smd_Contract, ContractDto>();
                //            var contractDto = Mapper.Map<t_smd_Contract, ContractDto>(contract);
                //            store.contract = contractDto;

                //            #region 获取门店终止合同并绑定
                //            if (key == Constant.PROCESS_CHANGEDEALER)
                //            {
                //                var ContractCancel = ContractService.GetContractCancelByStoreID(store.StoreID);
                //                Mapper.CreateMap<t_smd_Contract_Cancel, ContractCancelDto>();
                //                var cancelDto = Mapper.Map<t_smd_Contract_Cancel, ContractCancelDto>(ContractCancel);
                //                store.contract.StoreCancel = cancelDto;
                //            }
                //        }
                //            #endregion

                //    }
                //}

                if (storeDataIds.Count() > 0)
                {
                    var storeContract = (t_smd_Store._StoreID.In(storeDataIds)).List<t_smd_Store>(Storage.Context3).ToList();
                    foreach (var store in storeContract)
                    {
                        Mapper.CreateMap<t_smd_Store, StoreContractDto>();
                        newStorelist.Add(Mapper.Map<t_smd_Store, StoreContractDto>(store));
                    }

                    var contractList = (t_smd_Contract._StoreID.In(storeDataIds)).List<t_smd_Contract>(Storage.Context3).ToList();
                    foreach (var store in newStorelist)
                    {
                        var contract = (t_smd_Contract._StoreID == store.StoreID).ListFirst<t_smd_Contract>(Storage.Context3);
                        if (contract != null)
                        {
                            var storeContractLog = result_logs.Where(t => t.DataID == contract.ContractID.ToString() & t.Category == "BatchChangeContract").ToList();
                            if (storeContractLog.Count > 0)
                            {
                                contract = DataHelper<t_smd_Contract>.Reload(contract, storeContractLog);
                            }
                            Mapper.CreateMap<t_smd_Contract, ContractDto>();
                            var contractDto = Mapper.Map<t_smd_Contract, ContractDto>(contract);
                            store.contract = contractDto;

                            #region 获取门店终止合同并绑定
                            if (key == Constant.PROCESS_CHANGEDEALER)
                            {
                                var ContractCancel = ContractService.GetContractCancelByStoreID(store.StoreID);
                                Mapper.CreateMap<t_smd_Contract_Cancel, ContractCancelDto>();
                                var cancelDto = Mapper.Map<t_smd_Contract_Cancel, ContractCancelDto>(ContractCancel);
                                store.contract.StoreCancel = cancelDto;
                            }
                        }
                            #endregion
                    }
                }

                if (newStorelist.Count > 0)
                {

                    foreach (StoreContractDto conDto in newStorelist)
                    {
                        var deviceDataIds = logs.Where(c => c.Category == "BatchChangeContractDevice").Select(t => Convert.ToInt32(t.DataID)).Distinct();
                        var donestoreId = new List<int>();
                        if (deviceDataIds != null && deviceDataIds.Count() > 0)
                        {
                            conDto.devices = new List<ContractDeviceDto>();
                            var logDevice = new List<t_smd_ContractDevice>();
                            Mapper.CreateMap<t_smd_Contract, ContractDeviceDto>();
                            var deviceContracts = (t_smd_ContractDevice._ContractDeviceID.In(deviceDataIds)).List<t_smd_ContractDevice>(Storage.Context3).ToList();

                            foreach (var deviceContract in deviceContracts)
                            {
                                if (conDto.StoreID == deviceContract.StoreID)
                                {
                                    var _logs = result_logs.Where(t => t.DataID == deviceContract.ContractDeviceID.ToString() & t.Category == "BatchChangeContractDevice").ToList();
                                    Mapper.CreateMap<t_smd_ContractDevice, ContractDeviceDto>();
                                    t_smd_ContractDevice device1 = DataHelper<t_smd_ContractDevice>.Reload(deviceContract, _logs);
                                    ContractDeviceDto deviceDto = Mapper.Map<t_smd_ContractDevice, ContractDeviceDto>(device1);
                                    if (TaskAPI.GetVariableBySingleValue("AutoBusinessKey") ==
                                        Constant.PROCESS_CHANGEDEALER)
                                    {
                                        var deviceCancel =
                                        (t_smd_ContractDevice_Cancel._DeviceID == deviceDto.DeviceID)
                                            .ListFirst<t_smd_ContractDevice_Cancel>(Storage.Context3, "ContractDeviceCancelID desc");// 注释 2016-11-20 Add
                                        Mapper.CreateMap<t_smd_ContractDevice_Cancel, ContractDeviceCancelDto>();
                                        var deviceCancelDto = Mapper.Map<t_smd_ContractDevice_Cancel, ContractDeviceCancelDto>(deviceCancel);
                                        deviceDto.DeviceCancel = deviceCancelDto;
                                    }

                                    conDto.devices.Add(deviceDto);
                                    donestoreId.Add(conDto.StoreID);
                                }
                            }
                            if (!donestoreId.Contains(conDto.StoreID))
                            {
                                Mapper.CreateMap<t_smd_ContractDevice, ContractDeviceDto>();
                                var deviceContract = (t_smd_ContractDevice._StoreID == conDto.StoreID).ListFirst<t_smd_ContractDevice>(Storage.Context3);
                                if (deviceContract != null)
                                {
                                    ContractDeviceDto deviceDto = Mapper.Map<t_smd_ContractDevice, ContractDeviceDto>(deviceContract);
                                    if (TaskAPI.GetVariableBySingleValue("AutoBusinessKey") ==
                                                Constant.PROCESS_CHANGEDEALER)
                                    {
                                        var deviceCancel = ContractDeviceService.getCotractDeviceCancelByDeviceID(deviceContract.DeviceID);

                                        Mapper.CreateMap<t_smd_ContractDevice_Cancel, ContractDeviceCancelDto>();
                                        var deviceCancelDto = Mapper.Map<t_smd_ContractDevice_Cancel, ContractDeviceCancelDto>(deviceCancel);
                                        deviceDto.DeviceCancel = deviceCancelDto;
                                    }
                                    conDto.devices.Add(deviceDto);
                                }                                
                            }
                        }

                    }
                }
                #endregion

                storelist = newStorelist;
            }
            #endregion

            return storelist;
        }

    }
}